/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2016 All Rights Reserved.
 */
package com.fulihui.integral.core.handler;

import com.fulihui.integral.core.request.ISUserBehaviorReq;
import com.fulihui.mscore.api.MessageService;
import com.fulihui.mscore.enums.MsgTypeEnum;
import com.fulihui.mscore.request.MsgCreateRequest;
import org.near.servicesupport.request.RequestBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;



import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangyingjie
 * @version $Id: v 0.1 2017年06月15日 15:37 zhangyingjie Exp $
 */
@Component("integralMsgBusinessSelector")
public class IntegralMsgBusinessSelector extends ApplicationObjectSupport {
    private transient Logger log = LoggerFactory.getLogger(getClass());

    private Map<String, IntegralMsgBusinessHandler> handlers = new HashMap<>();
    @Autowired
    private MessageService messageService;

    @PostConstruct
    void init() {
        Map<String, AbstractIntegralMsgBusinessHandler> beansOfType = getApplicationContext()
                .getBeansOfType(AbstractIntegralMsgBusinessHandler.class);
        beansOfType.values().forEach(it -> handlers.put(it.getMsgType().getCode(), it));
        log.info("Registered handlers size: {}", handlers.size());
    }

    private IntegralMsgBusinessHandler getHandler(String type) {
        return handlers.get(type);
    }

    /**
     * @param request
     */
    public void doHandler(ISUserBehaviorReq request) {
        IntegralMsgBusinessHandler handler = getHandler(request.getIsChannelType());
        if (handler != null) {
            handler.handle(request);
        }

        //TODO 所有的积分变动都进行一次站内消息提醒，暂时写在这儿，后期拆分
        MsgCreateRequest msgCreateRequest = new MsgCreateRequest();
        msgCreateRequest.setTarget(request.getUserId());
        msgCreateRequest.setMsgType(MsgTypeEnum.MESSAGE_JIFEN.getCode());
        messageService.createMsg(RequestBuilder.buildT(msgCreateRequest));
    }
}
